package chapter6;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

//LC 102 二叉树的层序遍历
public class BinaryTreeLevelOrderTraversal {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    static class Pair {
        int level;
        TreeNode node;
        Pair(int level, TreeNode node) {
            this.level = level;
            this.node = node;
        }
    }

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null){
            return res;
        }
        Queue<Pair> queue = new LinkedList<>();
        queue.offer(new Pair(0, root));
        while (!queue.isEmpty()) {
            Pair pair = queue.poll();
            int level = pair.level;
            TreeNode node = pair.node;

            if (level == res.size()) {
                res.add(new ArrayList<Integer>());
            }
            res.get(level).add(node.val);
            if (node.left != null) {
                queue.offer(new Pair(level + 1, node.left));
            }
            if (node.right != null) {
                queue.offer(new Pair(level + 1, node.right));
            }
        }
        return res;

    }
}
